package cn.exrick.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.exrick.common.exception.XmallException;
import cn.exrick.common.jedis.JedisClient;
import cn.exrick.mapper.TbItemCatMapper;
import cn.exrick.mapper.TbItemDescMapper;
import cn.exrick.mapper.TbItemMapper;
import cn.exrick.pojo.TbItem;
import cn.exrick.pojo.TbItemCat;
import cn.exrick.pojo.TbItemDesc;
import cn.exrick.pojo.TbItemExample;
import cn.exrick.pojo.TbItemSkuCat;
import cn.exrick.pojo.TbItemSkuCatAttr;
import cn.exrick.pojo.TbItemSkuGoodCat;
import cn.exrick.pojo.TbItemSkuGoodCatAttr;
import cn.exrick.pojo.common.DataTablesResult;
import cn.exrick.pojo.dto.ItemDto;
import cn.exrick.service.ItemService;
import cn.exrick.service.ItemSkuCatAttrService;
import cn.exrick.service.ItemSkuCatService;
import cn.exrick.service.ItemSkuGoodCatAttrService;
import cn.exrick.service.ItemSkuGoodCatService;
import cn.exrick.service.SearchItemService;
import cn.exrick.utils.DtoUtil;
import cn.exrick.utils.IDUtil;

/**
 * Created by Exrick on 2017/7/29.
 */
@Service
public class ItemServiceImpl implements ItemService {

    private final static Logger log = LoggerFactory.getLogger(ItemServiceImpl.class);

    @Autowired
    private TbItemMapper tbItemMapper;

    @Autowired
    private TbItemDescMapper tbItemDescMapper;

    @Autowired
    private TbItemCatMapper tbItemCatMapper;

    @Autowired
    private SearchItemService searchItemService;

    @Autowired
    private JedisClient jedisClient;

    @Value("${PRODUCT_ITEM}")
    private String PRODUCT_ITEM;

    @Autowired
    private ItemSkuCatService itemSkuCatService;
    @Autowired
    private ItemSkuGoodCatService itemSkuGoodCatService;
    @Autowired
    private ItemSkuCatAttrService itemSkuCatAttrService;
    @Autowired
    private ItemSkuGoodCatAttrService itemSkuGoodCatAttrService;

    @Override
    public ItemDto getItemById(Long id) {
        TbItem tbItem = tbItemMapper.selectByPrimaryKey(id);
        if(null == tbItem){
            return null;
        }
        ItemDto itemDto = DtoUtil.TbItem2ItemDto(tbItem);

        TbItemCat tbItemCat = tbItemCatMapper.selectByPrimaryKey(itemDto.getCid());
        itemDto.setCname(tbItemCat == null?"":tbItemCat.getName());

        TbItemDesc tbItemDesc = tbItemDescMapper.selectByPrimaryKey(id);
        if(tbItemDesc != null){
            itemDto.setDetail(tbItemDesc.getItemDesc());
        }

        return itemDto;
    }

    @Override
    public TbItem getNormalItemById(Long id) {

        return tbItemMapper.selectByPrimaryKey(id);
    }

    @Override
    public DataTablesResult getItemList(int draw, int start, int length, int cid, String search,
                                        String orderCol, String orderDir) {

        DataTablesResult result = new DataTablesResult();

        //分页执行查询返回结果
        PageHelper.startPage(start / length + 1, length);
        List<TbItem> list = tbItemMapper.selectItemByCondition(cid, "%" + search + "%", orderCol, orderDir);
        PageInfo<TbItem> pageInfo = new PageInfo<>(list);
        result.setRecordsFiltered((int) pageInfo.getTotal());
        result.setRecordsTotal(getAllItemCount().getRecordsTotal());

        result.setDraw(draw);
        result.setData(list);

        return result;
    }

    @Override
    public DataTablesResult getItemSearchList(int draw, int start, int length, int cid, String search,
                                              String minDate, String maxDate, String orderCol, String orderDir) {

        DataTablesResult result = new DataTablesResult();

        //分页执行查询返回结果
        PageHelper.startPage(start / length + 1, length);
        List<TbItem> list = tbItemMapper.selectItemByMultiCondition(cid, "%" + search + "%", minDate, maxDate, orderCol, orderDir);
        PageInfo<TbItem> pageInfo = new PageInfo<>(list);
        result.setRecordsFiltered((int) pageInfo.getTotal());
        result.setRecordsTotal(getAllItemCount().getRecordsTotal());

        result.setDraw(draw);
        result.setData(list);

        return result;
    }

    @Override
    public DataTablesResult getAllItemCount() {
        TbItemExample example = new TbItemExample();
        Long count = tbItemMapper.countByExample(example);
        DataTablesResult result = new DataTablesResult();
        result.setRecordsTotal(Math.toIntExact(count));
        return result;
    }

    @Override
    public TbItem alertItemState(Long id, Integer state) {

        TbItem tbMember = getNormalItemById(id);
        tbMember.setStatus(state.byteValue());
        tbMember.setUpdated(new Date());

        if (tbItemMapper.updateByPrimaryKey(tbMember) != 1) {
            throw new XmallException("修改商品状态失败");
        }
        return getNormalItemById(id);
    }

    @Override
    public int deleteItem(Long id) {

        if (tbItemMapper.deleteByPrimaryKey(id) != 1) {
            throw new XmallException("删除商品失败");
        }
        if (tbItemDescMapper.deleteByPrimaryKey(id) != 1) {
            throw new XmallException("删除商品详情失败");
        }
        //发送消息同步索引库
        try {
            searchItemService.refreshItem(1, id);
        } catch (Exception e) {
            log.error(e.toString());
        }
        return 0;
    }

    @Override
    public TbItem addItem(ItemDto itemDto) {
        long id = IDUtil.getRandomId();
        TbItem tbItem = DtoUtil.ItemDto2TbItem(itemDto);
        tbItem.setId(id);
        tbItem.setStatus((byte) 1);
        tbItem.setCreated(new Date());
        tbItem.setUpdated(new Date());
        if (tbItem.getImage().isEmpty()) {
            tbItem.setImage("http://ow2h3ee9w.bkt.clouddn.com/nopic.jpg");
        }
        if (tbItemMapper.insert(tbItem) != 1) {
            throw new XmallException("添加商品失败");
        }

        TbItemDesc tbItemDesc = new TbItemDesc();
        tbItemDesc.setItemId(id);
        tbItemDesc.setItemDesc(itemDto.getDetail());
        tbItemDesc.setCreated(new Date());
        tbItemDesc.setUpdated(new Date());

        if (tbItemDescMapper.insert(tbItemDesc) != 1) {
            throw new XmallException("添加商品详情失败");
        }
        //发送消息同步索引库
        try {
            searchItemService.refreshItem(0, id);
        } catch (Exception e) {
            log.error(e.toString());
        }
        return getNormalItemById(id);
    }

    @Override
    public void addItems(String sku, ItemDto itemDto) throws Exception {
        try {
            JSONObject json = JSONObject.parseObject(sku);
            Map map = json.getInnerMap();
            saveSku(map,null,itemDto);
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("sku勾选错误");
        }
    }

    public void saveSku(Map map,Long fatherCatAttrId,ItemDto itemDto) throws Exception {
        if(map.size()<=0){
            return;
        }
        Object key = map.keySet().iterator().next();
        Object value = map.get(key);
        Long catId = Long.parseLong((String) key);
        TbItemSkuCat cat = itemSkuCatService.findById(catId);
        if (cat == null) {
            throw new Exception("没找到一级分类");
        }
        TbItemSkuGoodCat itemSkuGoodCat = new TbItemSkuGoodCat();
        if (fatherCatAttrId != null) {
            itemSkuGoodCat.setFatherItemSkuGoodCatId(fatherCatAttrId);
        }
        itemSkuGoodCat.setName(cat.getName());

        itemSkuGoodCatService.save(itemSkuGoodCat);
        itemSkuGoodCat.setId(itemSkuGoodCat.getId());

        String attrsStr = (String) value;
        String[] attrs = attrsStr.split(",");
        int i = 0;
        for (String attrStr : attrs) {
            Long attrId = Long.parseLong(attrStr);
            TbItemSkuCatAttr itemSkuCatAttr = itemSkuCatAttrService.findById(attrId);
            if (itemSkuCatAttr == null) {
                throw new Exception("没有找到二级分类");
            }
            TbItemSkuGoodCatAttr itemSkuGoodCatAttr = new TbItemSkuGoodCatAttr();

            if (map.size()==1) {//到了叶节点
                TbItem item = addItem(itemDto);
                itemSkuGoodCatAttr.setItemId(item.getId());
                itemSkuGoodCatAttr.setItemSkuGoodCatId(itemSkuGoodCat.getId());
                itemSkuGoodCatAttr.setName(itemSkuCatAttr.getName());
                itemSkuGoodCatAttr.setSortIndex(i);
                i++;
                itemSkuGoodCatAttrService.save(itemSkuGoodCatAttr);
            }else{
                itemSkuGoodCatAttr.setItemSkuGoodCatId(itemSkuGoodCat.getId());
                itemSkuGoodCatAttr.setName(itemSkuCatAttr.getName());
                itemSkuGoodCatAttr.setSortIndex(i);
                i++;
                itemSkuGoodCatAttrService.save(itemSkuGoodCatAttr);
                long catAttrId = itemSkuGoodCatAttr.getId();
                Map nextMap = new HashMap();
                int index = 0;
                for(Object k:map.keySet()){
                    if(index != 0){
                        nextMap.put(k,map.get(k));
                    }
                    index++;
                }
                saveSku(nextMap,catAttrId,itemDto);
            }
        }
    }

    @Override
    public TbItem updateItem(Long id, ItemDto itemDto) {

        TbItem oldTbItem = getNormalItemById(id);

        TbItem tbItem = DtoUtil.ItemDto2TbItem(itemDto);

        if (tbItem.getImage().isEmpty()) {
            tbItem.setImage(oldTbItem.getImage());
        }
        tbItem.setId(id);
        tbItem.setStatus(oldTbItem.getStatus());
        tbItem.setCreated(oldTbItem.getCreated());
        tbItem.setUpdated(new Date());
        if (tbItemMapper.updateByPrimaryKey(tbItem) != 1) {
            throw new XmallException("更新商品失败");
        }

        TbItemDesc tbItemDesc = new TbItemDesc();

        tbItemDesc.setItemId(id);
        tbItemDesc.setItemDesc(itemDto.getDetail());
        tbItemDesc.setUpdated(new Date());
        tbItemDesc.setCreated(oldTbItem.getCreated());

        if (tbItemDescMapper.updateByPrimaryKey(tbItemDesc) != 1) {
            throw new XmallException("更新商品详情失败");
        }
        //同步缓存
        deleteProductDetRedis(id);
        //发送消息同步索引库
        try {
            searchItemService.refreshItem(0, id);
        } catch (Exception e) {
            log.error(e.toString());
        }
        return getNormalItemById(id);
    }

    //同步商品详情缓存
    public void deleteProductDetRedis(Long id) {
        try {
            jedisClient.del(PRODUCT_ITEM + ":" + id);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
